package com.ruoyi.yiqikan.controller;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.yiqikan.domain.VideoRoom;
import com.ruoyi.yiqikan.service.SocketIoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

/**
 * 17kan插件接口
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/yiqikan")
public class LoginController {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SocketIoService socketIoService;

    @PostMapping("/logout")
    @ResponseBody
    public String onLogoutSuccess(HttpServletRequest request,@RequestBody VideoRoom videoRoom){
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
            if(StringUtils.isNotEmpty(videoRoom.getRoomId())){
                socketIoService.exitRoom(videoRoom.getRoomId(),userName);
            }
        }
        return JSON.toJSONString(AjaxResult.success("退出成功"));
    };
}
